//
//  addZJRJViewController.m
//  Estate
//
//  Created by heyong on 16/6/25.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "H1_ImagesCell.h"
#import "TableTopStateCell.h"
#import "JLRJTitleCell.h"
#import "DefaineCell.h"
#import "B_wuLiaoCell.h"
#import "PictureViewController.h"


#import "GJDBViewController_Detail.h"
#import "SGFDBDetailViewController.h"
#import "JLAddJLViewController.h"
#import "DiaryModel.h"
#import "FMDatabaseAdditions.h"
#import "addDiaryHeadView.h"
//#import "UIActionSheet+Common.h"
#import "PatrolDetailViewController.h"
#import "SafeDetailViewController.h"

#import "addZJRJViewController.h"


@interface addZJRJViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextViewDelegate>
{
    DiaryModel *_model;
}

@property (strong, nonatomic) Tweet *curTweet;
/**tableView*/
@property (strong ,nonatomic)TPKeyboardAvoidingTableView *tableView;

@property(strong, nonatomic)NSMutableArray *fileArr;
//天气
@property(strong ,nonatomic)NSMutableArray *weatherArr;

@property(strong ,nonatomic)NSMutableArray *dataArray;
@property (strong, nonatomic)NSMutableArray *selectedAssetURLs;
//提交数据存储
@property(strong, nonatomic)NSMutableDictionary *subDic;
@property(strong, nonatomic)FMDatabase *db;

@end

@implementation addZJRJViewController

- (NSMutableArray *)weatherArr {
    if(_weatherArr==nil){
        _weatherArr=[NSMutableArray array];
    }
    return _weatherArr;
}

- (NSMutableArray *)fileArr{
    if(_fileArr==nil){
        _fileArr=[NSMutableArray array];
    }
    return _fileArr;
}

- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

//懒加载
- (NSMutableArray *)dataArray {
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return  _dataArray;
}

- (NSMutableDictionary *)subDic {
    if(_subDic==nil){
        _subDic=[NSMutableDictionary dictionary];
    }
    return _subDic;
}

- (FMDatabase *)db {
    if(_db==nil){
        _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    }
    return _db;
}

- (TPKeyboardAvoidingTableView *)tableView {
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"dCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"JLRJTitleCell" bundle:nil] forCellReuseIdentifier:@"titleCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"sCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"日记";
    self.view.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    // 添加右上方提交按钮
    if(![self.flag isEqualToString:@"look"]){
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
        self.isEdit=YES;
    }
    
    _curTweet = [[Tweet alloc] init];
    [self.view addSubview:self.tableView];
    [self setData];
    [self refresh:nil];
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_rj_1" object:nil];
}

- (void)setIds:(NSString *)ids {
    _ids = ids;
    _model = [[DiaryModel alloc] init];
    NSString *sqlStr=[NSString stringWithFormat:@" select substr(DIARY_TIME,1,10) AS Day,* from work_diary where id='%@'", ids];
    [self.db open];
    FMResultSet *results=[self.db executeQuery:sqlStr];
    while ([results next]) {
        _model.diaryId = [results stringForColumn:@"ID"];
        _model.PRO_ID=[results stringForColumn:@"PRO_ID"];
        _model.DIARY_USER= [LSUtility getuserIdByUserName:
                            [results stringForColumn:@"DIARY_USER"]][@"REAL_NAME"];
        _model.DIARY_TYPE=[results stringForColumn:@"DIARY_TYPE"];
        _model.DIARY_DESC=[results stringForColumn:@"DIARY_DESC"];
        _model.day=[results stringForColumn:@"Day"];
        _model.CREATE_TIME=[results stringForColumn:@"CREATE_TIME"];
        _model.DIARY_TIME=[results stringForColumn:@"DIARY_TIME"];
        _model.TOUR_INFO=[results stringForColumn:@"TOUR_INFO"];
        _model.EXTEND_INFO=[results stringForColumn:@"EXTEND_INFO"];
        _model.CHECK_INFO=[results stringForColumn:@"CHECK_INFO"];
        _model.WEATHER=[results stringForColumn:@"WEATHER"];
        _model.SITE_INFO=[results stringForColumn:@"SITE_INFO"];
        _model.SUPERVISE_INFO=[results stringForColumn:@"SUPERVISE_INFO"];
        _model.FOLLOW_INFO=[results stringForColumn:@"FOLLOW_INFO"];
        _model.SAFE_INFO=[results stringForColumn:@"SAFE_INFO"];
        _model.OTHER_INFO=[results stringForColumn:@"OTHER_INFO"];
        //迭代新增类型 日记引入
        _model.JIANCHA_INFO=[results stringForColumn:@"JIANCHA_INFO"];
        _model.ZHILIANG_INFO=[results stringForColumn:@"ZHILIANG_INFO"];
        _model.JINDU_INFO=[results stringForColumn:@"JINDU_INFO"];
        _model.CAILIAO_INFO=[results stringForColumn:@"CAILIAO_INFO"];
        _model.YINBI_INFO=[results stringForColumn:@"YINBI_INFO"];
        _model.SHOUFAWEN_INFO=[results stringForColumn:@"SHOUFAWEN_INFO"];
        _model.JIANZHENG_INFO=[results stringForColumn:@"JIANZHENG_INFO"];
        _model.HUIYI_INFO=[results stringForColumn:@"HUIYI_INFO"];
        _model.PATROL_RECORD_INFO=[results stringForColumn:@"PATROL_RECORD_INFO"];
        _model.SAFE_RECORD_INFO=[results stringForColumn:@"SAFE_RECORD_INFO"];
        
        _model.ENTER_EXTER_COMM_INFO=[results stringForColumn:@"ENTER_EXTER_COMM_INFO"];
        _model.MEETING_INFO=[results stringForColumn:@"MEETING_INFO"];
        _model.REVIEW_INFO=[results stringForColumn:@"REVIEW_INFO"];
        _model.REVIEW_SCORE=[results stringForColumn:@"REVIEW_SCORE"];
        _model.REVIEW_USER=[results stringForColumn:@"REVIEW_USER"];
        _model.REVIEW_STATE=[results stringForColumn:@"REVIEW_STATE"];
        _model.FILEIDS=[results stringForColumn:@"FILEIDS"];
        _model.STATE=[results stringForColumn:@"STATE"];
        _model.CREATE_USER_NAME=[results stringForColumn:@"CREATE_USER_NAME"];
        _model.CREATE_IP=[results stringForColumn:@"CREATE_IP"];
        _model.LOCAL_MODIFY_STATE=[results stringForColumn:@"LOCAL_MODIFY_STATE"];
    }
    [self.db close];
}

- (void)refresh:(id)sender {
    if (self.selectedAssetURLs!=nil) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //设置图片
            self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
            //回到主线程来刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:self.dataArray.count+2]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

#pragma mark - 点击保存数据
- (void)clickSave {
    if([self.flag isEqualToString:@"add"]){//新增 或者 覆盖
        if([LSUtility isExistAndType]){
            [self alertShow:@"确定覆盖当前的日记吗?"];
        }else{
            [self addWorkDiary];
        }
    }else{ //查看编辑页
        if([LSUtility isExistAndType]){
            [self alertShow:@"确定修改当前的日记吗?"];
        }
    }
}

#pragma mark- 新增日记
- (void)addWorkDiary {
    
    // 附件表新增数据(日记ID)
    NSString *fileId = [NSUUID UUID].UUIDString;
    self.curTweet.selectedAssetURLs = [ self.curTweet.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    // 循环存入附件表
    if (self.curTweet.selectedAssetURLs.count>0) {
        // 附件表id
        for (int i=0; i<self.curTweet.selectedAssetURLs.count; i++) {
            NSString *ids=[NSUUID UUID].UUIDString;
            NSArray *arr=[self.curTweet.selectedAssetURLs[i] componentsSeparatedByString:@"/"];
            NSString *imageName = [arr lastObject];
            UIImage *image=[UIImage imageWithContentsOfFile:self.curTweet.selectedAssetURLs[i]];
            
            // 存入附件表
            [LSUtility insertAttachmentFromFileID:fileId andTableID:ids andImage:image andType:@"DIARY_01" andImageName:imageName];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:ids forKey:@"fileId"];
            [dict setObject:@"1" forKey:@"fileState"];
            [self.fileArr addObject:dict];
        }
    }
    
    // 日记表添加记录
    NSString *xunStr,*pangStr,*anStr,*duStr,*yanStr,*genStr,*qiStr,*jianchaStr,*zhiliangStr,*jinduStr,*cailiaoStr,*yinbiStr,*shoufawenStr,*jianzhengStr,*huiyiStr, *patrolStr, *safeStr;
    for (NSDictionary *dic in self.dataArray) {
        NSString *type=dic[@"title"];
        
        if([type isEqualToString:@"巡视记录"])
        {
            xunStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"旁站"])
        {
            pangStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"安全记录"])
        {
            anStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"其它"])
        {
            qiStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"督办"])
        {
            duStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"跟进"])
        {
            genStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"验收"])
        {
            yanStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"检查"])
        {
            jianchaStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"质量"])
        {
            zhiliangStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"进度"])
        {
            jinduStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"材料设备进场"])
        {
            cailiaoStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"隐蔽检查验收"])
        {
            yinbiStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"收发文"])
        {
            shoufawenStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"见证取样"])
        {
            jianzhengStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"会议及协调"])
        {
            huiyiStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"巡视"]) {
            patrolStr = [LSUtility toJSONData:dic[@"data"]];

        }
        else if ([type isEqualToString:@"安全"]) {
            safeStr = [LSUtility dictionaryToJson:dic[@"data"]];
        }
    }
    
    // 迭代 记录新增类型字段 判断有没有。没有数据库增加此字段。
    [self.db open];
    if (![self.db columnExists:@"ZHILIANG_INFO" inTableWithName:WORK_DIARY]){
        [self.db beginTransaction];
        
        NSString *alertStr1 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'JIANCHA_INFO' TEXT "];
        [self.db executeUpdate:alertStr1];
        
        NSString *alertStr2 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'ZHILIANG_INFO' TEXT"];
        [self.db executeUpdate:alertStr2];
        
        NSString *alertStr3 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'JINDU_INFO' TEXT"];
        [self.db executeUpdate:alertStr3];
        
        NSString *alertStr4 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'CAILIAO_INFO' TEXT"];
        [self.db executeUpdate:alertStr4];
        
        NSString *alertStr5 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'YINBI_INFO' TEXT"];
        [self.db executeUpdate:alertStr5];
        
        NSString *alertStr6 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'SHOUFAWEN_INFO' TEXT"];
        [self.db executeUpdate:alertStr6];
        
        NSString *alertStr7 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'JIANZHENG_INFO' TEXT"];
        [self.db executeUpdate:alertStr7];
        
        NSString *alertStr8 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'HUIYI_INFO' TEXT"];
        [self.db executeUpdate:alertStr8];
        
        // 巡视
        NSString *alertStr9 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'PATROL_RECORD_INFO' TEXT"];
        [self.db executeUpdate:alertStr9];
        
        // 安全
        NSString *alertStr10 = [NSString stringWithFormat:@"ALTER TABLE WORK_DIARY ADD 'SAFE_RECORD_INFO' TEXT"];
        [self.db executeUpdate:alertStr10];
        
        [self.db commit];
        [self.db close];
    }
    
    DBHelper *helper=[DBHelper help];
    NSDictionary *dic=@{
                        @"ID":fileId,
                        @"PRO_ID":PROID,
                        @"DIARY_USER":USERID,
                        @"DIARY_TYPE":@"DIARY_01",
                        @"REVIEW_TIME":@"",
                        @"DIARY_TIME":_model.DIARY_TIME,
                        @"TOUR_INFO":DEFISNUL(xunStr),
                        @"CHECK_INFO":DEFISNUL(yanStr),
                        @"SITE_INFO":DEFISNUL(pangStr),
                        @"WEATHER":_model.WEATHER,
                        @"SUPERVISE_INFO":DEFISNUL(duStr),
                        @"FOLLOW_INFO":DEFISNUL(genStr),
                        @"SAFE_INFO":DEFISNUL(anStr),
                        @"OTHER_INFO":DEFISNUL(qiStr),
                        //迭代新增类型
                        @"JIANCHA_INFO":DEFISNUL(jianchaStr),
                        @"ZHILIANG_INFO":DEFISNUL(zhiliangStr),
                        @"JINDU_INFO":DEFISNUL(jinduStr),
                        @"CAILIAO_INFO":DEFISNUL(cailiaoStr),
                        @"YINBI_INFO":DEFISNUL(yinbiStr),
                        @"SHOUFAWEN_INFO":DEFISNUL(shoufawenStr),
                        @"JIANZHENG_INFO":DEFISNUL(jianzhengStr),
                        @"HUIYI_INFO":DEFISNUL(huiyiStr),
                        @"PATROL_RECORD_INFO":DEFISNUL(patrolStr),
                        @"SAFE_RECORD_INFO":DEFISNUL(safeStr),
                        @"ENTER_EXTER_COMM_INFO":DEFISNUL(self.subDic[@"neib"]),//内外沟通
                        @"MEETING_INFO":DEFISNUL(self.subDic[@"huiy"]),//会议
                        @"REVIEW_INFO":@"",
                        @"REVIEW_SCORE":@"",
                        @"REVIEW_USER":@"",
                        @"REVIEW_STATE":@"1",
                        @"FILEIDS":[LSUtility dictionaryToJson_2:self.fileArr],
                        @"REVIEW_INFO":@"",
                        @"DIARY_DESC":DEFISNUL(self.subDic[@"qita"]),
                        @"EXTEND_INFO":@"",
                        @"STATE":@"0",
                        @"MODIFY_USER_NAME":@"",
                        @"MODIFY_IP":@"",
                        @"MODIFY_TIME":@"",
                        @"LOCAL_MODIFY_USER_NAME":@"",
                        @"CREATE_USER_NAME":@"anonymous",
                        @"CREATE_TIME":_model.DIARY_TIME,
                        @"CREATE_IP":[LSUtility getIPAddress],
                        @"LOCAL_MODIFY_STATE":@"ADD"
                        };
    
    BOOL isOK = [helper DataBase:self.db insertReplaceKeyValues:dic intoTable:WORK_DIARY];
    if (isOK) {
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_zj_rj" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        [MBProgressHUD showError:@"添加失败" toView:self.view];
    }
}

#pragma  mark - 修改数据
- (void)updateDatabase {
    // 附件表修改数据
    self.curTweet.selectedAssetURLs = [ self.curTweet.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    //循环存入附件表
    if(self.curTweet.selectedAssetURLs.count>0){
        // 附件表id
        [self.fileArr removeAllObjects];
        for (int i=0; i<self.curTweet.selectedAssetURLs.count; i++) {
            NSString *ids=[NSUUID UUID].UUIDString;
            NSArray *arr=[self.curTweet.selectedAssetURLs[i] componentsSeparatedByString:@"/"];
            NSString *imageName = [arr lastObject];
            UIImage *image=[UIImage imageWithContentsOfFile:self.curTweet.selectedAssetURLs[i]];
            
            // 存入附件表
            [LSUtility insertAttachmentFromFileID:_model.diaryId andTableID:ids andImage:image andType:@"DIARY_01" andImageName:imageName];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:ids forKey:@"fileId"];
            [dict setObject:@"1" forKey:@"fileState"];
            [self.fileArr addObject:dict];
        }
    }
    
    // 日记表修改
    
    NSString *xunStr,*pangStr,*anStr,*duStr,*yanStr,*genStr,*qiStr,*jianchaStr,*zhiliangStr,*jinduStr,*cailiaoStr,*yinbiStr,*shoufawenStr,*jianzhengStr,*huiyiStr, *patrolStr, *safeStr;
    for (NSDictionary  *dic in self.dataArray) {
        NSString *type=dic[@"title"];
        
        if([type isEqualToString:@"巡视记录"])
        {
            xunStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"旁站"])
        {
            pangStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"安全记录"])
        {
            anStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"其它"])
        {
            qiStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"督办"])
        {
            duStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"跟进"])
        {
            genStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"验收"])
        {
            yanStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"检查"])
        {
            jianchaStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"质量"])
        {
            zhiliangStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"进度"])
        {
            jinduStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"材料设备进场"])
        {
            cailiaoStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"隐蔽检查验收"])
        {
            yinbiStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"收发文"])
        {
            shoufawenStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"见证取样"])
        {
            jianzhengStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"会议及协调"])
        {
            huiyiStr=[LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"巡视"])
        {
            patrolStr = [LSUtility dictionaryToJson:dic[@"data"]];
        }
        else if ([type isEqualToString:@"安全"])
        {
            safeStr = [LSUtility dictionaryToJson:dic[@"data"]];
        }
    }
    
    DBHelper *helper=[DBHelper help];
    NSDictionary *dic=@{
                        @"DIARY_TYPE":@"DIARY_01",
                        @"DIARY_TIME":_model.DIARY_TIME,
                        @"TOUR_INFO":DEFISNUL(xunStr),
                        @"CHECK_INFO":DEFISNUL(yanStr),
                        @"SITE_INFO":DEFISNUL(pangStr),
                        @"WEATHER":_model.WEATHER,
                        @"SUPERVISE_INFO":DEFISNUL(duStr),
                        @"FOLLOW_INFO":DEFISNUL(genStr),
                        @"SAFE_INFO":DEFISNUL(anStr),
                        @"OTHER_INFO":DEFISNUL(qiStr),
                        //迭代新增类型
                        @"JIANCHA_INFO":DEFISNUL(jianchaStr),
                        @"ZHILIANG_INFO":DEFISNUL(zhiliangStr),
                        @"JINDU_INFO":DEFISNUL(jinduStr),
                        @"CAILIAO_INFO":DEFISNUL(cailiaoStr),
                        @"YINBI_INFO":DEFISNUL(yinbiStr),
                        @"SHOUFAWEN_INFO":DEFISNUL(shoufawenStr),
                        @"JIANZHENG_INFO":DEFISNUL(jianzhengStr),
                        @"HUIYI_INFO":DEFISNUL(huiyiStr),
                        @"PATROL_RECORD_INFO":DEFISNUL(patrolStr),
                        @"SAFE_RECORD_INFO":DEFISNUL(safeStr),
                        @"ENTER_EXTER_COMM_INFO":DEFISNUL(self.subDic[@"neib"]),//内外沟通
                        @"MEETING_INFO":DEFISNUL(self.subDic[@"huiy"]),//会议
                        @"FILEIDS":[LSUtility dictionaryToJson_2:self.fileArr],
                        @"DIARY_DESC":DEFISNUL(self.subDic[@"qita"]),
                        @"CREATE_TIME":_model.DIARY_TIME,
                        @"MODIFY_TIME":_model.DIARY_TIME,
                        @"LOCAL_MODIFY_STATE":@"MOD"
                        };
    
    
    [helper DataBase:self.db updateTable:WORK_DIARY setKeyValues:dic whereCondition:@{@"ID":_model.diaryId}];
    NSNotification *notice = [NSNotification notificationWithName:@"Refresh_zj_rj" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    // 通知首页刷新数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"home" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  mark - 设置数据
- (void)setData {
    // 存在值
    if (_model) {
        // 巡视记录
        NSArray *arr1 =[LSUtility dictionaryWithJsonString:_model.TOUR_INFO];
        //至少有一条数据添加到数据源
        if(arr1.count>0){
            NSDictionary *dic1=@{@"title":@"巡视记录",@"data":arr1};
            [self.dataArray addObject:dic1];
        }
        //验收
        NSArray *arr2 =[LSUtility dictionaryWithJsonString:_model.CHECK_INFO];
        if(arr2.count>0){
            NSDictionary *dic2=@{@"title":@"验收",@"data":arr2};
            [self.dataArray addObject:dic2];
        }
        //督办
        NSArray *arr3 =[LSUtility dictionaryWithJsonString:_model.SUPERVISE_INFO];
        if(arr3.count>0){
            NSDictionary *dic3=@{@"title":@"督办",@"data":arr3};
            [self.dataArray addObject:dic3];
        }
        //安全记录
        NSArray *arr4 =[LSUtility dictionaryWithJsonString:_model.SAFE_INFO];
        if(arr4.count>0){
            NSDictionary *dic4=@{@"title":@"安全记录",@"data":arr4};
            [self.dataArray addObject:dic4];
        }
        //跟进
        NSArray *arr5 =[LSUtility dictionaryWithJsonString:_model.FOLLOW_INFO];
        if(arr5.count>0){
            NSDictionary *dic5=@{@"title":@"跟进",@"data":arr5};
            [self.dataArray addObject:dic5];
        }
        //其它
        NSArray *arr6 =[LSUtility dictionaryWithJsonString:_model.OTHER_INFO];
        if(arr6.count>0){
            NSDictionary *dic6=@{@"title":@"其它",@"data":arr6};
            [self.dataArray addObject:dic6];
        }
        //检查
        NSArray *arr8 =[LSUtility dictionaryWithJsonString:_model.JIANCHA_INFO];
        if(arr8.count>0){
            NSDictionary *dic=@{@"title":@"检查",@"data":arr8};
            [self.dataArray addObject:dic];
        }
        //质量
        NSArray *arr9 =[LSUtility dictionaryWithJsonString:_model.ZHILIANG_INFO];
        if(arr9.count>0){
            NSDictionary *dic=@{@"title":@"质量",@"data":arr9};
            [self.dataArray addObject:dic];
        }
        //进度
        NSArray *arr10 =[LSUtility dictionaryWithJsonString:_model.JINDU_INFO];
        if(arr10.count>0){
            NSDictionary *dic=@{@"title":@"进度",@"data":arr10};
            [self.dataArray addObject:dic];
        }
        //材料设备进场
        NSArray *arr11 =[LSUtility dictionaryWithJsonString:_model.CAILIAO_INFO];
        if(arr11.count>0){
            NSDictionary *dic=@{@"title":@"材料设备进场",@"data":arr11};
            [self.dataArray addObject:dic];
        }
        //隐蔽检查验收
        NSArray *arr12 =[LSUtility dictionaryWithJsonString:_model.YINBI_INFO];
        if(arr12.count>0){
            NSDictionary *dic=@{@"title":@"隐蔽检查验收",@"data":arr12};
            [self.dataArray addObject:dic];
        }
        //收发文
        NSArray *arr13 =[LSUtility dictionaryWithJsonString:_model.SHOUFAWEN_INFO];
        if(arr13.count>0){
            NSDictionary *dic=@{@"title":@"收发文",@"data":arr13};
            [self.dataArray addObject:dic];
        }
        //见证取样
        NSArray *arr14 =[LSUtility dictionaryWithJsonString:_model.JIANZHENG_INFO];
        if(arr14.count>0){
            NSDictionary *dic=@{@"title":@"见证取样",@"data":arr14};
            [self.dataArray addObject:dic];
        }
        //会议及协调
        NSArray *arr15 =[LSUtility dictionaryWithJsonString:_model.HUIYI_INFO];
        if(arr15.count>0){
            NSDictionary *dic=@{@"title":@"会议及协调",@"data":arr15};
            [self.dataArray addObject:dic];
        }
        // 巡视
        NSArray *arr16 = [LSUtility dictionaryWithJsonString:_model.PATROL_RECORD_INFO];
        if (arr16.count > 0) {
            NSDictionary *dic=@{@"title":@"巡视",@"data":arr16};
            [self.dataArray addObject:dic];
        }
        // 安全
        NSArray *arr17 = [LSUtility dictionaryWithJsonString:_model.SAFE_RECORD_INFO];
        if (arr17.count > 0) {
            NSDictionary *dic=@{@"title":@"安全",@"data":arr17};
            [self.dataArray addObject:dic];
        }
        
        //设置附件
        NSArray *imageArr=[LSUtility dictionaryWithJsonString:_model.FILEIDS];
        //查询附件表
        if(imageArr.count>0){
            for (NSDictionary *imageDic in imageArr) {
                NSString *fileId=imageDic[@"fileId"];
                NSString *fileName=[LSUtility queryAttachment:fileId][@"FILE_NAME"];
                NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                    [NSString stringWithFormat:@"/%@",fileName]];
                [self.selectedAssetURLs addObject:filePath];
            }
        }
        self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
        [self refresh:nil];
        
    } else {
        //天气数组
        NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
        if(wArr.count>0){
            for (NSDictionary *wdic in wArr) {
                for (NSString *city in wdic) {
                    [self.weatherArr addObject:city];
                }
            }
        }
        //新增页 从其他表提取 (一键生成)
        [self createData];
    }
}


#pragma mark - 生成日记
- (void)createData {
    //默认数据
    _model=[[DiaryModel alloc]init];
    //当前时间
    _model.day=[LSUtility dateNow];
    _model.DIARY_USER=DEF_PERSISTENT_GET_OBJECT(@"realname");
    _model.PRO_ID=PROID;
    
    //天气数组
    NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
    if(wArr.count>0){
        NSDictionary *dic=[wArr firstObject];
        NSString *deCity=[self.weatherArr firstObject];
        _model.WEATHER=[NSString stringWithFormat:@"%@/%@",deCity,dic[deCity]];
    }
    
    if([self.flag isEqualToString:@"look"]){
        
    }else{
        _model.DIARY_TIME=[LSUtility nowTime];
    }
    
    //督办
    _model.SUPERVISE_INFO=[self selectProcessBytype:@"1" andTime:[LSUtility dateNow]];
    
    //跟进
    _model.FOLLOW_INFO=[self selectProcessBytype:@"2" andTime:[LSUtility dateNow]];
    
    //验收
    _model.CHECK_INFO=[self selectProcessBytype:@"3" andTime:[LSUtility dateNow]] ;
    
    //巡视记录 RECORD_01
    _model.TOUR_INFO=[self selectRecordForType:@"RECORD_01" andTime:[LSUtility dateNow]];
    
    //安全记录 RECORD_03
    _model.SAFE_INFO =[self selectRecordForType:@"RECORD_03" andTime:[LSUtility dateNow]];
    
    //其他 RECORD_04
    _model.OTHER_INFO=[self selectRecordForType:@"RECORD_04" andTime:[LSUtility dateNow]];
    
    //检查 RECORD_07
    _model.JIANCHA_INFO=[self selectRecordForType:@"RECORD_07" andTime:[LSUtility dateNow]];
    
    //质量 RECORD_08
    _model.ZHILIANG_INFO=[self selectRecordForType:@"RECORD_08" andTime:[LSUtility dateNow]];
    
    //进度 RECORD_09
    _model.JINDU_INFO=[self selectRecordForType:@"RECORD_09" andTime:[LSUtility dateNow]];
    
    //材料设备进场 RECORD_10
    _model.CAILIAO_INFO=[self selectRecordForType:@"RECORD_10" andTime:[LSUtility dateNow]];
    
    //隐蔽检查验收 RECORD_11
    _model.YINBI_INFO=[self selectRecordForType:@"RECORD_11" andTime:[LSUtility dateNow]];
    
    //收发文 RECORD_12
    _model.SHOUFAWEN_INFO=[self selectRecordForType:@"RECORD_12" andTime:[LSUtility dateNow]];
    
    //见证取样 RECORD_13
    _model.JIANZHENG_INFO=[self selectRecordForType:@"RECORD_13" andTime:[LSUtility dateNow]];
    
    //会议及协调 RECORD_14
    _model.HUIYI_INFO=[self selectRecordForType:@"RECORD_14" andTime:[LSUtility dateNow]];
    
    // 巡视
    _model.PATROL_RECORD_INFO = [self selectTodayPatrol:_model.day];
    
    // 安全
    _model.SAFE_RECORD_INFO = [self selectTodaySafe:_model.day];
    
    [self setData];
}

// 查询流程表
- (NSString *)selectProcessBytype:(NSString *)type andTime:(NSString *)time{
    //一键式查询数据
    [self.db open];
    NSString *proId=_model.PRO_ID;
    NSString *userid=DEF_PERSISTENT_GET_OBJECT(@"userid");
    
    NSString *sql;
    if([type isEqualToString:@"2"]){
        sql=[NSString stringWithFormat:@"select ID ,PROCESS_TYPE,PROCESS_TITLE from PROCESS where date(CREATE_TIME) ='%@' AND pro_id='%@' AND PROCESS_TYPE='%@'  ",time,proId,type];
        
    }else if ([type isEqualToString:@"3"]){
        sql=[NSString stringWithFormat:@"select ID ,PROCESS_TYPE,PROCESS_TITLE,PROCESS_STAGE,EXTEnD_INFO from PROCESS where pro_id='%@' AND  PROCESS_TYPE='3' AND (date(create_time)='%@' or date(MODIFY_TIME)='%@')",proId,time,time];
        
    } else {
        sql=[NSString stringWithFormat:@"select ID ,PROCESS_TYPE,PROCESS_TITLE from PROCESS where date(CREATE_TIME) ='%@' AND pro_id='%@' AND PROCESS_TYPE='%@'",time,proId,type];
    }
    
    FMResultSet *result=[self.db executeQuery:sql];
    NSMutableArray *arrs=[NSMutableArray array];
    while ([result next]) {
        // 流程类型
        NSString *type = [result stringForColumn:@"PROCESS_TYPE"];
        NSString *str=[result stringForColumn:@"ID"];
        NSString *userName=[LSUtility getuserIdByUserName:userid][@"USER_NAME"];
        NSString *realName=[LSUtility getuserIdByUserName:userid][@"REAL_NAME"];
        
        NSString *sql_1=[NSString stringWithFormat:@"SELECT  id ,PROBLEM_TYPE FROM process_record where process_id='%@'",str];
        FMResultSet *result1=[self.db executeQuery:sql_1];
        NSString *problemType=@"";
        while ([result1 next]) {
            int i=[result1 intForColumn:@"PROBLEM_TYPE"];
            problemType=[NSString stringWithFormat:@"%i",i];
        }
        
        // 拼接标题
        NSString *title=@"";
        if([type isEqualToString:@"3"]){
            NSString *address_1=[result stringForColumn:@"EXTEND_INFO"];
            NSDictionary *add=[LSUtility dictionaryWithJsonString:address_1];
            address_1=[add objectForKey:@"address"];
            NSString *stage=[result stringForColumn:@"PROCESS_STAGE"];
            NSString *checkTitle=[result stringForColumn:@"PROCESS_TITLE"];
            
            if([stage isEqualToString:@"201"]||[stage isEqualToString:@"401"]||[stage isEqualToString:@"5"]){
                title=[NSString stringWithFormat:@"完成%@_%@ 合格",DEFISNUL(address_1),checkTitle];
                
            }else if([stage isEqualToString:@"4"]||[stage isEqualToString:@"2"]){
                title=[NSString stringWithFormat:@"完成%@_%@ 待验收",DEFISNUL(address_1),checkTitle];
            } else {
                title=[NSString stringWithFormat:@"完成%@_%@ 不合格",DEFISNUL(address_1),checkTitle];
            }
        }else{
            title=[result stringForColumn:@"PROCESS_TITLE"];
        }
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        // 流程类型
        [dic setValue:type forKey:@"recordType"];
        [dic setValue:realName forKey:@"realname"];
        [dic setValue:userName forKey:@"username"];
        [dic setValue:str forKey:@"recordId"];
        [dic setValue:title forKey:@"info"];
        [dic setValue:problemType forKey:@"problemType"];
        [dic setValue:USERID forKey:@"userid"];
        [arrs addObject:dic];
    }
    [self.db close];
    return [LSUtility dictionaryToJson:arrs];
}

//巡视安全其他查询记录表
-(NSString *)selectRecordForType:(NSString *)type andTime:(NSString *)time{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"select * from WORK_RECORD where date(CREATE_TIME) ='%@' AND pro_id='%@' AND RECORD_USER='%@' AND RECORD_TYPE in('%@') AND STATE='0'",time,PROID,USERID,type];
    
    FMResultSet *result=[db executeQuery:sql];
    NSMutableArray *arrs=[NSMutableArray array];
    while ([result next]) {
        // 类型
        NSString *type = [result stringForColumn:@"RECORD_TYPE"];
        NSString *str=[result stringForColumn:@"ID"];
        NSString *userName=[LSUtility getuserIdByUserName:USERID][@"USER_NAME"];
        NSString *realName=[LSUtility getuserIdByUserName:USERID][@"REAL_NAME"];
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        // 流程类型
        [dic setValue:type forKey:@"recordType"];
        [dic setValue:realName forKey:@"realname"];
        [dic setValue:userName forKey:@"username"];
        [dic setValue:str forKey:@"recordId"];
        //该内容为标题
        [dic setValue:[result stringForColumn:@"RECORDONTENT"] forKey:@"info"];
        [arrs addObject:dic];
    }
    [db close];
    return [LSUtility dictionaryToJson:arrs];
}

// 查询今天巡视
- (NSString *)selectTodayPatrol:(NSString *)date {
    //一键式查询数据
    [self.db open];
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM PATROL_RECORD WHERE PRO_ID = '%@' AND  RECORD_USER = '%@' AND date(CREATE_TIME) = '%@'", _model.PRO_ID, USERID, date];
    
    NSMutableArray *patrolArr = [NSMutableArray array];
    FMResultSet *result = [self.db executeQuery:sqlStr];
    while ([result next]) {
        // 类型
        NSString *type = [result stringForColumn:@"RECORD_TYPE"];
        NSString *str = [result stringForColumn:@"ID"];
        NSString *userName=[LSUtility getuserIdByUserName:USERID][@"USER_NAME"];
        NSString *realName=[LSUtility getuserIdByUserName:USERID][@"REAL_NAME"];
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [dic setValue:realName forKey:@"realname"];
        [dic setValue:userName forKey:@"username"];
        [dic setValue:str forKey:@"recordId"];
        // 改内容为标题
        [dic setValue:[result stringForColumn:@"MAJOR_INSPECT_DATA"] forKey:@"info"];
        [dic setValue:USERID forKey:@"userid"];
        // 流程类型
        [dic setValue:type forKey:@"recordType"];
        [patrolArr addObject:dic];
    }
    [self.db close];
    return [LSUtility dictionaryToJson_2:patrolArr];
}

// 查询今天安全
- (NSString *)selectTodaySafe:(NSString *)date {
    //一键式查询数据
    [self.db open];
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM SAFE_RECORD_BASIC WHERE PRO_ID = '%@' AND  RECORD_USER = '%@' AND date(CREATE_TIME) = '%@'", _model.PRO_ID, USERID, date];
    
    NSMutableArray *safeArr = [NSMutableArray array];
    FMResultSet *result = [self.db executeQuery:sqlStr];
    while ([result next]) {
        // 类型
        NSString *type = [result stringForColumn:@"RECORD_TYPE"];
        NSString *str = [result stringForColumn:@"ID"];
        NSString *userName=[LSUtility getuserIdByUserName:USERID][@"USER_NAME"];
        NSString *realName=[LSUtility getuserIdByUserName:USERID][@"REAL_NAME"];
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [dic setValue:realName forKey:@"realname"];
        [dic setValue:userName forKey:@"username"];
        [dic setValue:str forKey:@"recordId"];
        // 改内容为标题
        [dic setValue:[result stringForColumn:@"PROBLEM_AND_DEAL"] forKey:@"info"];
        [dic setValue:USERID forKey:@"userid"];
        // 流程类型
        [dic setValue:type forKey:@"recordType"];
        [safeArr addObject:dic];
    }
    [self.db close];
    return [LSUtility dictionaryToJson_2:safeArr];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count+3;
}

//返回组
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) // 第一组
    {
        return 6;
    }
    else if (section==self.dataArray.count+1) //倒数第二组
    {
        return 3;
    }
    else if (section==self.dataArray.count+2)  //最后一组
    {
        return 1;
    }
    else//查询动态添加组
    {
        NSArray *array=self.dataArray[section-1][@"data"];
        return array.count;
    }
}

// 每行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==self.dataArray.count+1)  //倒数第二组
    {
        return 120;
    }
    else if (indexPath.section==self.dataArray.count+2)//附件信息
    {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件信息"];
    }
    else
    {
        return 44;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    //第一组
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            TableTopStateCell  *cell=[tableView dequeueReusableCellWithIdentifier:@"dCell" forIndexPath:indexPath];
            cell.title.backgroundColor=[UIColor colorWithRed:0.85 green:0.93 blue:0.97 alpha:1.00];
            //标题
            NSString *title=[NSString stringWithFormat:@"%@总监日记",DEF_PERSISTENT_GET_OBJECT(@"realname")];
            cell.title.text=title;
            return cell;
            
        } else {
            if(indexPath.row==1){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                [cell setTitle:@"项    目:" andDetail:DEF_PERSISTENT_GET_OBJECT(@"proname") andLeftConstraint:8];
                [self.subDic setObject:DEF_PERSISTENT_GET_OBJECT(@"proname") forKey:@"proname"];
                return cell;
                
            }else if (indexPath.row==2){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                [cell setTitle:@"记 录 人:" andDetail:DEF_PERSISTENT_GET_OBJECT(@"realname") andLeftConstraint:8];
                [self.subDic setObject:DEF_PERSISTENT_GET_OBJECT(@"userid") forKey:@"userid"];
                return cell;
                
            } else if (indexPath.row==3) {
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                [cell setTitle:@"时    间:" andDetail: _model.DIARY_TIME andLeftConstraint:8];
                [self.subDic setObject:[LSUtility nowTime] forKey:@"time"];
                return cell;
                
            } else if(indexPath.row==4) {
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                NSString *diqu=[[_model.WEATHER componentsSeparatedByString:@"/"]firstObject];
                [cell setTitle:@"地    区:" andDetail:diqu andLeftConstraint:8];
                return cell;
                
            } else {
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                NSString *weather=[[_model.WEATHER componentsSeparatedByString:@"/"]lastObject];
                [cell setTitle:@"天   气:" andDetail:weather andLeftConstraint:8];
                return cell;
            }
        }
    } else if (indexPath.section==self.dataArray.count+1)//倒数第二组
    {
        B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
        if(indexPath.row==0){
            cell.textValueChangedBlock=^(NSString *value) {
                [self.subDic setObject:value forKey:@"neib"];
            };
            if(_model.ENTER_EXTER_COMM_INFO){
                [cell setTitle:@"内部沟通" andPlaceHolder:@"请手动填写" andTextValue: _model.ENTER_EXTER_COMM_INFO];
            }else{
                [cell setTitle:@"内部沟通" andPlaceHolder:@"请手动填写" andTextValue: self.subDic[@"neib"]];
            }
            
        } else if (indexPath.row==1) {
            cell.textValueChangedBlock=^(NSString *value){
                [self.subDic setObject:value forKey:@"huiy"];
            };
            if(_model.MEETING_INFO){
                [cell setTitle:@"会议情况" andPlaceHolder:@"请手动填写" andTextValue:_model.MEETING_INFO];
            }else{
                [cell setTitle:@"会议情况" andPlaceHolder:@"请手动填写" andTextValue:self.subDic[@"huiy"]];
            }
        }else{
            cell.textValueChangedBlock=^(NSString *value){
                [self.subDic setObject:value forKey:@"qita"];
            };
            if (_model.DIARY_DESC) {
                [cell setTitle:@"其他" andPlaceHolder:@"请手动填写" andTextValue:_model.DIARY_DESC];
            }else{
                [cell setTitle:@"其他" andPlaceHolder:@"请手动填写" andTextValue:self.subDic[@"qita"]];
            }
        }
        cell.isEdit=self.isEdit;
        return cell;
        
    }else if(indexPath.section==self.dataArray.count+2)//最后一组
    {
        WEAKSELF
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit=self.isEdit;
        [cell setTitle:@"附件"];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        //删除图片
        cell.deleteTweetImageBlockUrl = ^(TweetImage *toDelete,NSString *deurl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deurl];
            
            [weakSelf refresh:nil];
        };
        return cell;
        
    } else {
        JLRJTitleCell *cell=[tableView dequeueReusableCellWithIdentifier:@"titleCell" forIndexPath:indexPath];
        //得到数据
        NSDictionary *dict=self.dataArray[indexPath.section-1];
        NSMutableArray *arr=self.dataArray[indexPath.section-1][@"data"];
        NSDictionary *cellDataDic=arr[indexPath.row];
        
        cell.title.text=[cellDataDic[@"info"]isEqualToString:@""]?@"无":cellDataDic[@"info"];
        cell.isEdit=self.isEdit;
        //判断是否是查看页面
        if([self.flag isEqualToString:@"look"]){
            cell.str=@"look";
        }
        
        //执行编辑操作
        cell.textValueChangedBlock=^(NSString *value){
            //重新设置标题
            [cellDataDic setValue:value forKey:@"info"];
        };
        
        //执行删除操作
        cell.dltBlock=^{
            [arr removeObjectAtIndex:indexPath.row];
            
            //该组下没有任何内容 移除改组
            if(arr.count==0){
                [self.dataArray removeObject:dict];
                [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
            } else {
                @try {
                    //刷新表格
                    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationFade)];
                    
                } @catch (NSException *exception) {
                    
                    NSLog(@"error:%@",exception);
                    
                } @finally {
                    
                }
            }
            [self.tableView reloadData];
        };
        
        //详情信息
        cell.detailBlick=^{
            // 跳转控制器
            [weakSelf jumpCtrforType:cellDataDic[@"recordType"] andId:cellDataDic[@"recordId"]];
        };
        return cell;
    }
}

#pragma mark - 组头组尾
// 组头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0||section==self.dataArray.count+1||section==self.dataArray.count+2) {
        return 0.1;
        
    } else if (section==1){
        return 30.;
    }
    return 25;
}

//组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //第一组 最后一组
    if(section==0 ||section==self.dataArray.count+1||section==self.dataArray.count+2) {
        return nil;
        
    } else if(section==1) {
        addDiaryHeadView *headView=[[addDiaryHeadView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 30)];
        headView.title.text=self.dataArray[section-1][@"title"];
        return headView;
        
    } else {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
        UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(8, 8, DEF_SCREEN_WIDTH, 15)];
        titleLab.font=[UIFont systemFontOfSize:15.];
        view.backgroundColor=[UIColor whiteColor];
        titleLab.textColor=[UIColor colorWithRed:0.47 green:0.48 blue:0.49 alpha:1.00];
        titleLab.text=self.dataArray[section-1][@"title"];
        [view addSubview:titleLab];
        return view;
    }
}

// 组尾高
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section==0||section==self.dataArray.count+1){
        return 15;
    }
    return 1;
}

// 组尾
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    //第一组 和倒数第二组
    if(section==0||section==self.dataArray.count+1)
    {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH-20, 15)];
        view.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        //波浪线
        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
        img.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        img.image=[UIImage imageNamed:@"juchishang"];
        [view addSubview:img];
        return view;
        
    }else{
        //横线
        UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 1)];
        line.backgroundColor=[UIColor colorWithRed:0.89 green:0.89 blue:0.90 alpha:1.00];
        return line;
    }
}

#pragma mark- 根据类型 。跳转到相应的页面查看详情
- (void)jumpCtrforType:(NSString *)type andId:(NSString *)id{
    JLAddJLViewController *jilCtr=[[JLAddJLViewController alloc]init];
    if([type isEqualToString:@"RECORD_01"]||[type isEqualToString:@"RECORD_03"]||[type isEqualToString:@"RECORD_04"]||[type isEqualToString:@"RECORD_07"]||[type isEqualToString:@"RECORD_08"]||[type isEqualToString:@"RECORD_09"]||[type isEqualToString:@"RECORD_10"]||[type isEqualToString:@"RECORD_11"]||[type isEqualToString:@"RECORD_12"]||[type isEqualToString:@"RECORD_13"]||[type isEqualToString:@"RECORD_14"])//巡视 安全 其他
    {
        jilCtr.flag=@"look";
        jilCtr.recordId=id;
        [self.navigationController pushViewController:jilCtr animated:YES];
    }
    else if ([type isEqualToString:@"1"])   // 督办
    {
        //根据id 查询最后修改时间
        NSDictionary *dic=[self modifyForId:id];
        NSString *extend=dic[@"ADDRES_INFO"];
        NSString *beginTime=dic[@"BEGIN_TIME"];
        NSString *endTime=dic[@"END_TIME"];
        GJDBViewController_Detail *detail=[[GJDBViewController_Detail alloc]init];
        detail.beginTime=beginTime;
        detail.endTime=endTime;
        detail.addressInfo=extend;
        detail.processId=id;
        [self.navigationController pushViewController:detail animated:YES];
    }
    else if ([type isEqualToString:@"2"])
    {   // 跟进
        //根据id 查询最后修改时间
        NSDictionary *dic=[self modifyForId:id];
        NSString *extend=dic[@"ADDRES_INFO"];
        NSString *beginTime=dic[@"BEGIN_TIME"];
        NSString *endTime=dic[@"END_TIME"];
        SGFDBDetailViewController *GJDetail=[[SGFDBDetailViewController alloc]init];
        GJDetail.beginTime=beginTime;
        GJDetail.endTime=endTime;
        GJDetail.flag = @"detail";
        GJDetail.addressInfo=extend;
        GJDetail.processID =id;
        GJDetail.gengjing = YES;
        [self.navigationController pushViewController:GJDetail animated:YES];
    }
    else if ([type isEqualToString:@"PATROL_01"])
    { // 巡视
        PatrolDetailViewController *patrolVC = [[PatrolDetailViewController alloc] init];
        patrolVC.isDiary = YES;
        patrolVC.patrolModel = [self selectPatrolInformation:id];
        [self.navigationController pushViewController:patrolVC animated:YES];
    }
    else if ([type isEqualToString:@"SAFE_RECORD_01"] || [type isEqualToString:@"SAFE_RECORD_02"] || [type isEqualToString:@"SAFE_RECORD_03"] || [type isEqualToString:@"SAFE_RECORD_04"] || [type isEqualToString:@"SAFE_RECORD_05"])    // 安全
    {
        SafeDetailViewController *safeVC = [[SafeDetailViewController alloc] init];
        safeVC.isDiary = YES;
        safeVC.safeModel = [self selectSafeInformation:id];
        [self.navigationController pushViewController:safeVC animated:YES];
    }
    else
    {
        [LSUtility showToastWithMessage:@"数据不存在" inView:self.view Andtime:1.];
    }
}

// 查找巡视信息
- (PatrolRecord *)selectPatrolInformation:(NSString *)safeID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    // 查找基本数据
    NSString *baseStr = [NSString stringWithFormat:@"SELECT * FROM PATROL_RECORD WHERE ID = '%@'", safeID];
    
    PatrolRecord *model = [[PatrolRecord alloc]init];
    FMResultSet *results = [db executeQuery:baseStr];
    while ([results next]) {
        model.id = [results stringForColumn:@"ID"];
        model.proId = [results stringForColumn:@"PRO_ID"];
        model.supervisorProUnitId = [results stringForColumn:@"SUPERVISOR_PRO_UNIT_ID"];
        model.constructProUnitId = [results stringForColumn:@"CONSTRUCT_PRO_UNIT_ID"];
        model.supervisorProUnitName = [results stringForColumn:@"SUPERVISOR_PRO_UNIT_NAME"];
        model.constructProUnitName = [results stringForColumn:@"CONSTRUCT_PRO_UNIT_NAME"];
        model.supervisorContractNumber = [results stringForColumn:@"SUPERVISOR_CONTRACT_NUMBER"];
        model.constructContractNumber = [results stringForColumn:@"CONSTRUCT_CONTRACT_NUMBER"];
        model.recordUser = [results stringForColumn:@"RECORD_USER"];
        model.recordType = [results stringForColumn:@"RECORD_TYPE"];
        model.recordTitle = [results stringForColumn:@"RECORD_TITLE"];
        model.recordContent = [results stringForColumn:@"RECORD_CONTENT"];
        model.state = [results stringForColumn:@"STATE"];
        model.recordNumber = [results stringForColumn:@"RECORD_NUMBER"];
        model.startTime = [results stringForColumn:@"START_TIME"];
        model.endTime = [results stringForColumn:@"END_TIME"];
        model.startAndEndTime = [results stringForColumn:@"START_AND_END_TIME"];
        model.weather = [results stringForColumn:@"WEATHER"];
        model.addId = [results stringForColumn:@"ADD_ID"];
        model.addInfo = [results stringForColumn:@"ADD_INFO"];
        model.rangeAndPosition = [results stringForColumn:@"RANGE_AND_POSITION"];
        model.majorproAndPerson = [results stringForColumn:@"MAJORPRO_AND_PERSON"];
        model.majorInspectData = [results stringForColumn:@"MAJOR_INSPECT_DATA"];
        model.problemAndDeal = [results stringForColumn:@"PROBLEM_AND_DEAL"];
        model.extendInfo = [results stringForColumn:@"EXTEND_INFO"];
        model.createusername = [results stringForColumn:@"CREATE_USER_NAME"];
        model.createtime = [results stringForColumn:@"CREATE_TIME"];
        model.createip = [results stringForColumn:@"CREATE_IP"];
        model.modifyusername = [results stringForColumn:@"MODIFY_USER_NAME"];
        model.modifytime = [results stringForColumn:@"MODIFY_TIME"];
        model.modifyip = [results stringForColumn:@"MODIFY_IP"];
    }
    [db close];
    return model;
}

// 查找安全信息
- (SecurityRecordBasic *)selectSafeInformation:(NSString *)safeID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    // 查找基本数据
    NSString *baseStr = [NSString stringWithFormat:@"SELECT * FROM SAFE_RECORD_BASIC WHERE ID = '%@'", safeID];
    
    SecurityRecordBasic *model = [[SecurityRecordBasic alloc] init];
    FMResultSet *baseResult = [db executeQuery:baseStr];
    while ([baseResult next]) {
        model.id = [baseResult stringForColumn:@"ID"];
        model.proId = [baseResult stringForColumn:@"PRO_ID"];
        model.supervisorProUnitId = [baseResult stringForColumn:@"SUPERVISOR_PRO_UNIT_ID"];
        model.constructProUnitId = [baseResult stringForColumn:@"CONSTRUCT_PRO_UNIT_ID"];
        model.supervisorProUnitName = [baseResult stringForColumn:@"SUPERVISOR_PRO_UNIT_NAME"];
        model.constructProUnitName = [baseResult stringForColumn:@"CONSTRUCT_PRO_UNIT_NAME"];
        model.supervisorContractNumber = [baseResult stringForColumn:@"SUPERVISOR_CONTRACT_NUMBER"];
        model.constructContractNumber = [baseResult stringForColumn:@"CONSTRUCT_CONTRACT_NUMBER"];
        model.recordUser = [baseResult stringForColumn:@"RECORD_USER"];
        model.recordType = [baseResult stringForColumn:@"RECORD_TYPE"];
        model.recordTitle = [baseResult stringForColumn:@"RECORD_TITLE"];
        model.recordContent = [baseResult stringForColumn:@"RECORD_CONTENT"];
        model.state = [baseResult stringForColumn:@"STATE"];
        model.recordNumber = [baseResult stringForColumn:@"RECORD_NUMBER"];
        model.supervisorOpinion = [baseResult stringForColumn:@"SUPERVISOR_OPINION"];
        model.chiefSupervisorOpinion = [baseResult stringForColumn:@"CHIEF_SUPERVISOR_OPINION"];
        model.projectContent = [baseResult stringForColumn:@"PROJECT_CONTENT"];
        model.otherInfo = [baseResult stringForColumn:@"OTHER_INFO"];
        model.weather = [baseResult stringForColumn:@"WEATHER"];
        model.addId = [baseResult stringForColumn:@"ADD_ID"];
        model.addInfo = [baseResult stringForColumn:@"ADD_INFO"];
        model.extendInfo = [baseResult stringForColumn:@"EXTEND_INFO"];
        model.createusername = [baseResult stringForColumn:@"CREATE_USER_NAME"];
        model.createtime = [baseResult stringForColumn:@"CREATE_TIME"];
        model.createip = [baseResult stringForColumn:@"CREATE_IP"];
        model.modifyusername = [baseResult stringForColumn:@"MODIFY_USER_NAME"];
        model.modifytime = [baseResult stringForColumn:@"MODIFY_TIME"];
        model.modifyip = [baseResult stringForColumn:@"MODIFY_IP"];
        model.constructContractMoney = [baseResult stringForColumn:@"CONSTRUCT_CONTRACT_MONEY"];
        model.recifyState = [baseResult stringForColumn:@"RECIFY_STATE"];
        model.problemAndDeal = [baseResult stringForColumn:@"PROBLEM_AND_DEAL"];
        model.chiefSupervisorOpinionState = [baseResult stringForColumn:@"CHIEF_SUPERVISOR_OPINION_STATE"];
    }
    [db close];
    return model;
}

- (NSDictionary *)modifyForId:(NSString *)ids {
    DBHelper *helper=[DBHelper help];
    NSArray *dicArr= [helper DataBase:self.db selectKeyTypes:@{@"MODIFY_TIME":@"text",@"ADDRES_INFO":@"text",@"EXTEND_INFO":@"text",@"END_TIME":@"text",@"BEGIN_TIME":@"text"} fromTable:PROCESS whereCondition:@{@"ID":ids}] ;
    return  [dicArr firstObject];
}

#pragma mark- 点击表格 选择地区
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    if (self.isEdit && indexPath.section == 0 && indexPath.row == 4) {
        NSNumber *ninit = [NSNumber numberWithInteger:0];
        //天气数组
        NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
        if(!wArr){
            wArr=[NSMutableArray arrayWithObject:@{@"无":@"暂时无法获得天气信息"}];
        }
        if(self.weatherArr.count<1){
            [self.weatherArr addObject:@"无"];
        }
        
        [ActionSheetStringPicker showPickerWithTitle:nil rows:@[self.weatherArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
            
            int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
            NSDictionary *weadic=wArr[iv];
            NSString *weather =weadic[self.weatherArr[iv]];
            _model.WEATHER=[NSString stringWithFormat:@"%@/%@",self.weatherArr[iv],weather];
            //赋值
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
        } cancelBlock:nil origin:self.view];
    }
}

#pragma mark -- 提示语
- (void)alertShow:(NSString *)str{
    UIAlertAction *action=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self updateDatabase];
    }];
    
    UIAlertAction *cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertController *altCor=[UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
    [altCor addAction:action];
    [altCor addAction:cancel];
    [self presentViewController:altCor animated:YES completion:nil];
}

#pragma mark UIActionSheet M
- (void)showActionForPhoto {
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages=[[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            for (NSString *path in array) {
                //添加图片路径到已选数组
                [self.selectedAssetURLs addObject:path];
            }
        };
        
        [self.navigationController pushViewController:picCtr animated:YES];
        
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:weakSelf.dataArray.count+2]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end

